//
//  SNViewController.m
//  DayDayHappy
//
//  Created by yutao on 14-2-22.
//  Copyright (c) 2014年 yutao. All rights reserved.
//

#import "SNViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "SNAppDelegate.h"
#import "YIFullScreenScroll.h"
@interface SNViewController ()
{
    BOOL isRefreshLoding;
}
@end

@implementation SNViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dbHelper = [[SNAppDelegate sharedAppDelegate] dbHelper];
        self.contentDataArray = [[NSMutableArray alloc] initWithCapacity:1];
        isRefreshLoding = YES;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initContentTableView];
    
    [self initLoadingView];
    
    [self adjustsScrollViewInsetsIOS7];
    
    [self initPullToRefreshHeaderView];
    
    [self initPullToRefreshFooterView];
    
    
     __weak SNViewController * weakSelf = self;
    
    [self showLoading];
    [self.dbHelper search:[self currModel] where:[NSString stringWithFormat:@" type = '%@'",[self currentType]] orderBy:nil offset:0 count:20 callback:^(NSMutableArray *array) {
        if (array != nil && array.count>0) {
            weakSelf.contentDataArray = [NSMutableArray arrayWithArray:array];
            double delayInSeconds = 0.25;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [weakSelf.loadingView hideLoadingView];
                [weakSelf.contentTableView reloadData];
            });
            
        }else{
            [self sendDataRequestIsRefresh:NO];
        }
    }];


    
    
}
- (Class)currModel
{
    return [SNBaseModel class];
}

- (NSString *)currentType
{
    return @"";
}

- (void)initLoadingView
{
    self.loadingView = [[SNLoadingView alloc] initWithFrame:self.view.bounds];
    
    __weak typeof(self) weakSelf = self;
    self.loadingView.reloadCompletedBlock = ^(UIButton *sender) {
        // 这里可以做网络重新加载的地方
        [weakSelf sendDataRequestIsRefresh:NO];
    };
    [self.view addSubview:self.loadingView];
}

- (void)showLoading
{
    [self.loadingView showLoadingViewWithText:@"正在加载..." loadingAnimated:YES];
}

- (void)initContentTableView
{
    self.contentTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        self.contentTableView.frame  =  CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds) - ( CGRectGetHeight(self.navigationController.navigationBar.frame)));
    }else{
        self.contentTableView.frame  =CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds) - ( CGRectGetHeight(self.navigationController.navigationBar.frame)) - ( CGRectGetHeight(self.tabBarController.tabBar.frame)) -20);
    }
    self.contentTableView.delegate = self;
    self.contentTableView.dataSource = self;
    
    [self.view addSubview:self.contentTableView];
    
    
//    self.fullScreenScroll = [[YIFullScreenScroll alloc] initWithViewController:self scrollView:self.contentTableView style:YIFullScreenScrollStyleFacebook];
//    self.fullScreenScroll.shouldShowUIBarsOnScrollUp = NO;
}

- (void)initPullToRefreshHeaderView
{
    __weak SNViewController * weakSelf = self;
    [self.contentTableView addPullToRefreshWithActionHandler:^{
        [weakSelf newContentInsertTop];
    }];
}

- (void)initPullToRefreshFooterView
{
    __weak SNViewController * weakSelf = self;
    [self.contentTableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf nextPageContentInsertBottom];
    }];
}

- (void)adjustsScrollViewInsetsIOS7
{
    //修复iOS7 下拉刷新位置错误
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        
        UIEdgeInsets insets = self.contentTableView.contentInset;
        insets.top = self.navigationController.navigationBar.bounds.size.height +
        [UIApplication sharedApplication].statusBarFrame.size.height;
        self.contentTableView.contentInset = insets;
        self.contentTableView.scrollIndicatorInsets = insets;
    }

}

- (void)sendDataRequestIsRefresh:(BOOL)isRefresh
{
    //TODO  重复请求问题
    NSLog(@"RefreshUrl ======%@",self.requestUrl);
    
    isRefreshLoding = NO;
    __weak SNViewController * weakSelf = self;
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.requestUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    AFJSONRequestOperation *requestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.nextPage = [JSON objectForKey:kNextPageVersionArrayKey];
        isRefreshLoding = YES;
        
        if (isRefresh && ![self.currentVersion isEqual:[JSON valueForKey:kCurrVersionKey]])
        {
            if ([self isCommentModel]) {
                [weakSelf setUpNewestPageDataWith:[JSON objectForKey:@"comment_list"]];
            }else{
                [weakSelf setUpNewestPageDataWith:[JSON objectForKey:kContentsArrayKey]];
            }
        }
        else
        {
            [weakSelf.loadingView hideLoadingView];
            if ([self isCommentModel]) {
                [weakSelf setUpDataWith:[JSON objectForKey:@"comment_list"]];
            }else{
                [weakSelf setUpDataWith:[JSON objectForKey:kContentsArrayKey]];
            }
            
        }
        self.currentVersion = [JSON valueForKey:kCurrVersionKey];
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"******ERROR****** %@",[error description]);

        [weakSelf.loadingView showReloadViewWithText:@"加载失败，请点击刷新按钮重新加载。"];
        
    }];
    
    [requestOperation start];
    
}

- (void)sendDataRequestWihtUrl:(NSString *)urlStr
{
    NSLog(@"nextPageUrl ======%@",urlStr);
    __weak SNViewController * weakSelf = self;
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    AFJSONRequestOperation *requestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        
        self.nextPage = [JSON objectForKey:kNextPageVersionArrayKey];
        if ([self.nextPage intValue]!= -1) {
            if ([self isCommentModel]) {
                self.requestUrl = [self.requestUrl substringToIndex:[self.requestUrl rangeOfString:@"page"].location - 1];
            }else{
                self.requestUrl = [self.requestUrl substringToIndex:[self.requestUrl rangeOfString:@"&"].location];
            }
            
            if ([self isCommentModel]) {
                [weakSelf setUpNextPageDataWith:[JSON objectForKey:@"comment_list"]];
            }else{
                [weakSelf setUpNextPageDataWith:[JSON objectForKey:kContentsArrayKey]];
            }
            
        }else
        {
            [self.contentTableView.infiniteScrollingView stopAnimating];
        }
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"******ERROR****** %@",[error description]);
//        self.requestUrl = [self.requestUrl substringToIndex:[self.requestUrl rangeOfString:@"&"].location];
    }];
    
    [requestOperation start];
    
}

- (BOOL)isCommentModel
{
    return [self.requestUrl rangeOfString:@"comment"].location != NSNotFound;
}


- (void)setUpNextPageDataWith:(NSArray *)arrayFromJSON
{
    [self.contentTableView beginUpdates];
    [arrayFromJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SNBaseModel *imageModle =  [self currModelWithObj:obj];
        if (imageModle!= nil) {
            [self.contentDataArray addObject:imageModle];
            if (![self isCommentModel]) {
                [self.dbHelper insertWhenNotExists:imageModle];
            }
            
            [self.contentTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.contentDataArray.count-1 inSection:0]] withRowAnimation:0];
        }
    }];
    [self.contentTableView endUpdates];
    [self.contentTableView.infiniteScrollingView stopAnimating];
}

- (void)setUpNewestPageDataWith:(NSArray *)arrayFromJSON
{
    [self.contentTableView beginUpdates];
    [arrayFromJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SNBaseModel *imageModle =  [self currModelWithObj:obj];
        if (imageModle!= nil) {
            [self.contentDataArray insertObject:imageModle atIndex:0];
            if (![self isCommentModel]) {
//                [self.dbHelper insertWhenNotExists:imageModle];
            }
            
            [self.contentTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }];
    
    [self.contentTableView endUpdates];
    [self.contentTableView.pullToRefreshView stopAnimating];
}

- (void)setUpDataWith:(NSArray *)arrayFromJSON
{
    [arrayFromJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        SNBaseModel *imageModle =  [self currModelWithObj:obj];
        if (imageModle!= nil) {
            [self.contentDataArray addObject:imageModle];
            if (![self isCommentModel]) {
//                [self.dbHelper insertWhenNotExists:imageModle];
            }
            
        }
    }];
    [self.contentTableView reloadData];
    [self.contentTableView.pullToRefreshView stopAnimating];
}
- (SNBaseModel *)currModelWithObj:(id)obj
{
    return [[SNImageModel alloc] initWithDictionary:obj error:nil];
}

//下拉刷新
- (void)newContentInsertTop
{
    if (isRefreshLoding) {
        [self sendDataRequestIsRefresh:YES];
    }
    
    
}

//分页
-(void)nextPageContentInsertBottom
{
    if ([self.requestUrl rangeOfString:@"next_ver"].location == NSNotFound) {
        self.requestUrl = [self createNextPageRequestUrl];
        [self sendDataRequestWihtUrl:self.requestUrl];
    }
    
}

- (NSString *)createNextPageRequestUrl
{
    return [self.requestUrl stringByAppendingString:[NSString stringWithFormat:@"&next_ver=%@",self.nextPage]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contentDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CGRectGetHeight([self tableView:tableView cellForRowAtIndexPath:indexPath].frame);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}

- (BOOL)isiOS7
{
    return SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0");
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
@end
